<template>
  <!--悬停按钮-->
  <el-tooltip :content="value" placement="top">
    <el-switch
        v-model="value"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-value="编辑模式"
        inactive-value="查看模式"
        style="width: 3rem;height: 3rem;position: fixed;bottom: 4rem;right: 0.5rem;z-index: 9999;"
    />
  </el-tooltip>
  <!--文件树-->
  <div style="width: 15%; float: left; height:100%; position: fixed; z-index: 80">
    <el-card class="box-card" style="height: 100%">
      <template #header>
        <div class="card-header">
          <span style="margin-left: 25px"><strong>目录</strong></span>
          <span style="float: right; margin-right: 25px;"> <add-folder :fileFolder=rootPath @add="getFileFolder()"></add-folder></span>

          <!--                    <el-button class="button" type="text">Operation button</el-button>-->
        </div>
      </template>
      <el-tree :data="fileTree"
               :props="defaultProps"
               @node-click="handleNodeClick">
        <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span>
                    <add-folder v-if="data.children != null" :fileFolder=data.path @add="getFileFolder()"></add-folder>
                  <!--                <a @click="append(data)"><i class="el-icon-folder-add" v-if="data.children != null"></i></a>-->
                  <!--                <a @click="addFile(data)"><i class="el-icon-plus" v-if="data.children != null"></i></a>-->
                    <add-file v-if="data.children != null" :fileFolder=data.path @add="getFileFolder()"></add-file>
                    <el-popconfirm title="确认删除文件夹或文件？" @confirm="delFolder(data)">
                        <template #reference>
                            <a><i class="el-icon-delete"></i></a>
                        </template>
                    </el-popconfirm>
                </span>
              </span>
        </template>
      </el-tree>
    </el-card>
  </div>
  <!--编辑器-->
  <div style="width: 85%; float: right; height:100%;">
    <!--标题-->
    <div style="position: fixed; width: 100%;z-index: 2">
      <el-input v-model="title" disabled placeholder="请输入标题">
        <template #prepend>标题</template>
      </el-input>
    </div>
    <div style="width: 100%; height:100%;z-index: 1">
      <div style="height: 40px;"></div>
      <!--markdown编辑器-->
      <v-md-editor v-if="value == '编辑模式'"
                   v-model="text"
                   :disabled-menus="[]"
                   @upload-image="handleUploadImage"
                   height="95%" @save="saveFile"></v-md-editor>

      <v-md-preview :text="text" height="95%"
                    v-if="value == '查看模式'"></v-md-preview>
    </div>

  </div>

</template>

<script>
import {ref} from 'vue'
import {saveFile} from '../api/login'
import {ElMessage} from 'element-plus'
import {getFileTree} from '../api/file'
import AddFolder from "../components/AddFolder";
import AddFile from "../components/AddFile";
import {delFile, parseFile, uploadFile} from '../api/file'
import {bookImgUrl} from "../config/globalConst";

export default {
  data() {
    return {
      text: '',
      title: ref(''),
      fileTree: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      value: '查看模式',
      currentPath: '',
      imgName: '',
      rootPath: ''
    }
  },

  components: {
    AddFolder,
    AddFile
  },
  methods: {
    saveFile(text) {
      // 下载到本地
      // const element = document.createElement('a');
      // element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      // element.setAttribute('download', this.title + ".md");
      // element.click();
      if (this.currentPath.split('.').length == 1) {
        return;
      }


      saveFile({"fileName": this.currentPath, "text": text})
          .then(res => {
            if (res.data.code == 200) {
              ElMessage.success("保存成功");
            } else {
              ElMessage.error("保存失败");
            }
          })
    },
    handleNodeClick(data) {
      // 保存功能
      this.saveFile(this.text);
      console.log(data);
      if (data.children == null) {
        parseFile({"dirName": data.path})
            .then(ref => {
              if (ref.data.code == 200) {
                this.text = ref.data.data;
                this.title = data.name.split(".")[0]
              } else {
                console.log("获取失败")
              }
            })
      }
      this.currentPath = data.path
    },
    append(data) {
      console.log(data)
    },
    remove(node, data) {
      console.log(node);
      console.log(data)
    },
    delFolder(data) {
      console.log(data.path)
      delFile({"dirName": data.path})
          .then(ref => {
            if (ref.data.code == 200) {
              ElMessage.success("删除成功")
              this.getFileFolder()
            } else {
              ElMessage.error("删除失败")
            }
          })
    },
    getFileFolder() {
      getFileTree()
          .then(res => {
            {
              if (res.data.code === 200) {
                this.fileTree = res.data.data.children;
                this.rootPath = res.data.data.path;
                this.rootFolder = res.data.data.name;
              } else {
                ElMessage.error("获取文件系统失败");
              }
            }
          })
    },
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      let param = new FormData();
      param.append("file", files[0]);
      uploadFile(param)
          .then(ref => {
            if (ref.data.code == 200) {
              this.imgName = ref.data.data;
              insertImage({
                url:
                    bookImgUrl + this.imgName,
                desc: '',
                width: 'auto',
                height: 'auto',
              });
            } else {
              ElMessage.error("上传失败");
            }
          });
    },
  },
  created() {
    this.getFileFolder();
    this.axios.get('/api/tokenVerify', {
      headers: {
        "Authorization": this.$store.state.token
      }
    })
        .then(response => {
          if (response.data.code == 200) {
            console.log("验证成功");
            console.log(response.data);
          } else if (response.data.code == 401) {
            this.$router.push('/login')
          } else {
            console.log("服务异常")
          }
        })

  }
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
